package com.lsf.base_android.utils;

import java.util.Stack;

import android.app.Activity;
import android.util.Log;

/**
 *  Activity 堆栈管理
 * @author lsf
 * @time 2016/1/21 16:45
 */
public class ActivityUtil {

    private static ActivityUtil instance;
    private Stack<Activity> activityStack;// activity栈

    // 单例模式
    public static ActivityUtil getInstance() {
        if (instance == null) {
            instance = new ActivityUtil();
        }
        return instance;
    }

    // 把一个activity压入栈中
    public void pushOneActivity(Activity activity) {

        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
        Log.d("MyActivityManager ", "size = " + activityStack.size());
    }

    // 获取栈顶的activity，先进后出原则
    public Activity getLastActivity() {
        return activityStack.lastElement();
    }

    // 获取栈顶的activity
    public <T> Activity getActivity(Class<T> clazz) {
        // TODO Auto-generated method stub
        for (int i = 0; i < activityStack.size(); i++) {
            Activity a = activityStack.get(i);
            if (a.getClass() == clazz) {
                return a;
            }
        }
        return null;
    }

    // 移除一个activity
    public void popOneActivity(Activity activity) {

        if (activityStack != null && activityStack.size() > 0) {
            if (activity != null) {
                activity.finish();
                activityStack.remove(activity);
                activity = null;
            }

        }
    }

    // 退出所有activity
    public void finishAllActivity() {
        if (activityStack != null) {
            while (activityStack.size() > 0) {
                Activity activity = getLastActivity();
                if (activity == null)
                    break;
                popOneActivity(activity);
            }
        }
    }
}
